﻿#region

using System;
using System.Net;
using System.Net.Sockets;

#endregion

namespace Lunexx.Network.World
{
    public class WorldListener : Listener
    {
        #region Constructors & Deconstructors

        public WorldListener(int listenPort, IPEndPoint serverIp, int serverPort)
            : base(listenPort, serverIp, serverPort)
        {
        }

        public WorldListener(IPAddress listenAddress, int listenPort, IPEndPoint server)
            : base(listenAddress, listenPort, server)
        {
        }

        public WorldListener(IPAddress listenAddress, int listenPort, IPAddress serverAddress, int serverPort)
            : base(listenAddress, listenPort, serverAddress, serverPort)
        {
        }

        #endregion

        #region Methods

        public override void OnAccept(IAsyncResult asResult)
        {
            try
            {
                var newSocket = ListenSocket.EndAccept(asResult);

                if (newSocket != null)
                {
                    ConsoleWrapper.WorldWriteLine("New connection accepted from: " + newSocket.RemoteEndPoint.ToString(), 1);
                    var newClient = new WorldClient(newSocket,new DestroyDelegate(this.RemoveClient),Server);
                    AddClient(newClient);
                    newClient.StartHandshake();
                    
                }
            }
            catch
            {
                try
                {
                    ListenSocket.BeginAccept(new AsyncCallback(this.OnAccept), ListenSocket);

                }
                catch (Exception e)
                {
                   // Dispose();
                    ConsoleWrapper.DebugWrite(e.ToString(),1);
                }
            }
        }
        protected override void InfoWrite(string input, byte loglevel)
        {
            ConsoleWrapper.WorldWriteLine(input,loglevel);
        }

        #endregion
    }
}